package com.csmy.my.center.util.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.csmy.my.center.action.OrderInfoAction;
import com.csmy.my.center.module.MyOrderInfo;
import com.csmy.my.center.module.OrderInfo;
import com.csmy.my.center.util.CTUtils;
import com.csmy.my.center.util.FileUtils;
import com.csmy.my.center.util.RequestUtil;
import com.csmy.my.center.util.StringUtil;
import com.csmy.my.center.util.dataconvert.Dto;
import com.csmy.my.center.util.dataconvert.impl.BaseDto;
import com.csmy.my.center.util.db.JdbcTemplateTool;
import com.csmy.my.center.util.report.excel.JxlsUtil;
import com.csmy.my.center.util.sms.SMS_Sender;

public class ImportCustOrderServlet extends HttpServlet {

	private static final long serialVersionUID = 1612258309532189663L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

	    	doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String returnMsg = "内部错误：上传文件失败!";
        StringUtil.xprint("开始上传文件....");
		resp.setContentType("text/html; charset=UTF-8");
		//文件上传位置
		String savePath = req.getSession().getServletContext().getRealPath("/") + "upload/";
		String templateFile = OrderInfoAction.class.getClassLoader().getResource("").getPath();
		String xmlConfigPath = templateFile + "template/orderTemplate.xml";
		
		PrintWriter out = null;
		try {
			out = resp.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (!ServletFileUpload.isMultipartContent(req)) {
			out.println("请选择文件。");
			return;
		}
		// 检查目录
		File uploadDir = new File(savePath);
		if (!uploadDir.isDirectory()) {
			out.println("上传目录不存在。");
			return;
		}
		// 检查目录写权限
		if (!uploadDir.canWrite()) {
			out.println("上传目录没有写权限。");
			return;
		}
		
		//开始处理上传....
		try {
			
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			List items = upload.parseRequest(req);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				String fileName = item.getName();
			    System.out.println("fileName===="+fileName);
				long fileSize = item.getSize();
				if (!item.isFormField()) {
					
					SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
					String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + ".xls" ;
					try{
						File uploadedFile = new File(savePath, newFileName);
						item.write(uploadedFile);
					}catch(Exception e){
						out.println("上传文件失败。");
						return;
					}

					//处理订单数据
					JxlsUtil jUtil = new JxlsUtil();
			        List<OrderInfo> oList;
			        String xlsPath = savePath+"/"+newFileName;
			        StringUtil.xprint("xlsPath="+xlsPath);
			        MyOrderInfo orderInfo = jUtil.parseExcelFileToBeans(xlsPath,xmlConfigPath);
			        if(CTUtils.isNotEmpty(orderInfo)){
			        	Dto perDto = null;
			        	boolean bool = false;
			        	int countNum = 0;
						oList = orderInfo.getOrder();
						Dto perOrderInfo = null;
						if(CTUtils.isNotEmpty(orderInfo)){
							for (OrderInfo order : oList) {
								String order_id = order.getOrder_id();//订单编号
								String courier_id = order.getCourier_id();//快递单号
								String sender_type = order.getSender_type();//快递公司
								//判断订单是否存在
								perDto = new BaseDto();
								perDto.put("order_id", order_id);
								perOrderInfo = JdbcTemplateTool.getOrderByID(order_id);
								//订单存在且未发货
								if(CTUtils.isNotEmpty(perOrderInfo) && perOrderInfo.getAsString("state").equals("2")){
									//单号和公司同时不能为空
									if(CTUtils.isNotEmpty(courier_id) && CTUtils.isNotEmpty(sender_type)){
										perDto.put("optype", "mod_order");
										//处理科学计数法
										String courier_id1 = null;
										if(courier_id.contains("E")&&courier_id.contains(".")){
											BigDecimal bd = new BigDecimal(courier_id);  
											courier_id1 = bd.toPlainString();
											StringUtil.xprint("处理科学计数法后结果："+courier_id1);
										}else{
											courier_id1 = courier_id;
										}
										perDto.put("courier_id", courier_id1);
										perDto.put("sender_type", sender_type);
										//设置状态为已发货
										perDto.put("state", "4");
										bool = JdbcTemplateTool.updateOrder(perDto);
										if(bool){
										   countNum++;
										   //添加日志
										   JdbcTemplateTool.addOrderLog(order_id, "已发货、待签收");
										}
										
										/*************************发送短信开始*************************/
						        		String send_sms = CTUtils.getParamValue("SEND_DELIVERY_SMS");
						        		String send_sms_temp = CTUtils.getParamValue("SEND_SMS_TEMPLATE");
						        		if(CTUtils.isNotEmpty(send_sms) && send_sms.equals("1") && CTUtils.isNotEmpty(send_sms_temp)){
						        			String buyer_name = perOrderInfo.getAsString("buyer_name");
						        			String buyer_phone = perOrderInfo.getAsString("buyer_phone");
						        			String orderid = perOrderInfo.getAsString("order_id");
						        			String order_money = perOrderInfo.getAsString("sku_price");
						        			int bnum = perOrderInfo.getAsInteger("buy_num");
						        			double totalMoney = Double.valueOf(order_money)*bnum;
						        			
						        			if(send_sms_temp.contains("buyer_name")){
						        				send_sms_temp = send_sms_temp.replaceAll("\\$buyer_name", buyer_name);
						        			}
						        			if(send_sms_temp.contains("order_id")){
						        				send_sms_temp = send_sms_temp.replaceAll("\\$order_id", orderid);
						        			}
						        			if(send_sms_temp.contains("order_money")){
						        				send_sms_temp = send_sms_temp.replaceAll("\\$order_money", ""+totalMoney);
						        			}
						        			
						        			String smString = send_sms_temp;
						        			StringUtil.xprint("发送批量发货提示短信内容为>>>"+smString);
						        			if(SMS_Sender.sendSms(buyer_phone, smString)){
						    					StringUtil.xprint("批量发货提示发送成功!");
						    				}else{
						    					StringUtil.xprint("批量发货提示短信发送失败!");
						    				}
						        		}
						        		/*************************发短信件结束*************************/
						        		
									}else{
										returnMsg = "对不起！导入的excel文件缺少核心数据【快递单号、快递公司编号】!";
									}
								}
							}
							//处理返回信息
							returnMsg = "共【"+oList.size()+"】条数据,导入成功【"+countNum+"】条!";
						}else{
							returnMsg = "对不起！导入的excel文件没有相关数据!";
				        }
			        }else{
			        	returnMsg = "对不起！导入的excel文件数据为空!";
			        }
					
					//导入完成后删除xls文档
					FileUtils fileUtils = new FileUtils();
					fileUtils.delFile(xlsPath);
				}
			}
			
		} catch (Exception e) {
			returnMsg = "导入数据过程出现错误！";
			e.printStackTrace();
		}finally{
			RequestUtil.renderHtml("<script>alert('"+returnMsg+"');window.location.href='"+req.getContextPath()+"/cust/order/list/2'</script>");
		}
		
		
	}

}
